<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 顶部搜索区域 -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" clearable v-model="queryData.query" @clear="getUserList()">
            <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
          </el-input> 
        </el-col>   <el-row :gutter="20">
  
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 中间表格区域 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <!-- 添加作用域插槽 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <!-- 添加作用域插槽 -->
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editInefo(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="角色分配" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="rolesAssign(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 底部分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 点击添加对话框 -->
    <!-- 头部 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%">
      <!-- 主体内容 -->
      <el-form :model="ruleForm" :rules="addUserRules" ref="ruleForm" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密　码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮　箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手　机" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 点击编辑对话框 -->
    <!-- 头部提示信息 -->
    <el-dialog title="修改用户信息" :visible.sync="dialogVisible_edit" width="30%">
      <!-- 主体内容 -->
      <el-form :model="ruleForm_edit" :rules="addUserRules" ref="ruleForm_edit" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm_edit.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮　箱" prop="email">
          <el-input v-model="ruleForm_edit.email"></el-input>
        </el-form-item>
        <el-form-item label="手　机" prop="mobile">
          <el-input v-model="ruleForm_edit.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer">
        <el-button @click="dialogVisible_edit = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 点击分配对话框 -->
    <!-- 头部提示信息 -->
    <el-dialog
      title="分配角色"
      :visible.sync="rolesAssignDialogVisible"
      width="50%"
      @close="closeRolesAssign"
    >
      <!-- 主体内容 -->
      <div>
        <p>
          当前用户：
          {{rolesAssignInfo.username}}
        </p>
        <p>
          当前角色：
          {{rolesAssignInfo.role_name}}
        </p>
        <p>
          分配新角色：
          <el-select v-model="seleteId" placeholder="请选择">
            <el-option v-for="item in arr" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </p>
      </div>
      <!-- 底部按钮 -->
      <span slot="footer">
        <el-button @click="rolesAssignDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureRolesAssign">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //已经选中的角色id
      seleteId: "",
      // 所有角色列表
      arr: [],
      // 分配角色数据
      rolesAssignInfo: {},
      // 分配角色对话框隐藏与否
      rolesAssignDialogVisible: false,
      // 添加用户对话框隐藏与否
      dialogVisible: false,
      // 修改用户对话框隐藏与否
      dialogVisible_edit: false,
      // 请求参数
      queryData: {
        query: "",
        pagenum: 1,
        pagesize: 10,
      },
      // 总数
      total: 0,
      // 请求结果数据
      userList: [],
      //添加用户表单
      ruleForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //编辑用户表单
      ruleForm_edit: {
        id: "",
        username: "",
        email: "",
        mobile: "",
      },
      //添加用户表单验证规则
      addUserRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
            message: "格式不正确",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
            message: "格式不正确",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getUserList();
  },
  watch: {
    dialogVisible(value) {
      if (!value) {
        this.$refs.ruleForm.resetFields();
      }
    },
  },
  methods: {
    //获取渲染用户列表
    async getUserList() {
      const { data: res } = await this.axios.get("users", {
        params: this.queryData,
      });
      if (res.meta.status !== 200) {
        return layer.msg("获取管理员列表失败！", { time: 1000 });
      }
      this.total = res.data.total;
      this.userList = res.data.users;
    },
    // 监听页面大小改变事件
    handleSizeChange(newSize) {
      // console.log(newSize);
      this.queryData.pagesize = newSize;
      this.getUserList();
    },
    // 监听页面发生改变事件
    handleCurrentChange(newPage) {
      // console.log(newPage);
      this.queryData.pagenum = newPage;
      this.getUserList();
    },
    // 监听用户状态改变事件
    userStatus(data) {
      layer.confirm(
        "确定改变当前用户状态码？",
        {
          icon: 3,
          title: "提示",
          btn: ["确定", "取消"],
          // 点击X号
          cancel: (index) => {
            data.mg_state = !data.mg_state;
            layer.close(index);
          },
        },
        // 确定按钮
        async (index) => {
          const { data: res } = await this.axios.put(
            `users/${data.id}/state/${data.mg_state}`
          );
          if (res.meta.status !== 200) {
            data.mg_state = !data.mg_state;
            return layer.msg(res.meta.msg, { time: 1000 });
          }
          layer.msg("修改成功！", { time: 1000 });
          layer.close(index);
        },
        // 取消按钮
        () => {
          data.mg_state = !data.mg_state;
        }
      );
    },
    //点击确定添加用户
    addUser() {
      this.$refs.ruleForm.validate(async (value) => {
        if (!value) {
          return layer.msg("输入不正确！", { time: 1000 });
        }
        const { data: res } = await this.axios.post("users", this.ruleForm);
        if (res.meta.status !== 201) {
          return layer.msg(res.meta.msg, { time: 1000 });
        }
        layer.msg("添加成功！", { time: 1000 }, () => {
          this.getUserList();
          //关闭对话框
          this.dialogVisible = false;
        });
      });
    },
    // 编辑用户按钮
    async editInefo(id) {
      this.dialogVisible_edit = true;
      // 发送请求
      const { data: res } = await this.axios.get("users/" + id);
      if (res.meta.status !== 200) {
        return layer.msg(res.meta.msg, { time: 1000 });
      }
      //获取成功
      this.ruleForm_edit.id = res.data.id;
      this.ruleForm_edit.username = res.data.username;
      this.ruleForm_edit.email = res.data.email;
      this.ruleForm_edit.mobile = res.data.mobile;
    },
    // 提交用户编辑修改
    editUser() {
      //预校验
      this.$refs.ruleForm_edit.validate(async (value) => {
        if (!value) {
          return layer.msg("输入不正确！", { time: 1000 });
        }
        const { data: res } = await this.axios.put(
          "users/" + this.ruleForm_edit.id,
          { email: this.ruleForm_edit.email, mobile: this.ruleForm_edit.mobile }
        );
        console.log(res);
        if (res.meta.status !== 200) {
          return layer.msg(res.meta.msg, { time: 1000 });
        }
        layer.msg("修改成功！", { time: 1000 });
        this.getUserList();
        //关闭对话框
        this.dialogVisible_edit = false;
      });
    },
    //删除按钮
    deleteUser(id) {
      layer.confirm(
        "确定要删除该用户吗",
        { icon: 3, title: "提示" },
        async (index) => {
          const { data: res } = await this.axios.delete("users/" + id);
          if (res.meta.status !== 200) {
            return layer.msg(res.meta.msg, { time: 1000 });
          }
          layer.msg(res.meta.msg, { time: 1000 }, () => {
            this.getUserList();
            layer.close(index);
          });
        }
      );
    },
    //分配角色按钮
    async rolesAssign(info) {
      this.rolesAssignInfo = info;
      const { data: res } = await this.axios.get("roles");
      if (res.meta.status !== 200) {
        return layer.msg(res.meta.msg, { time: 1000 });
      }
      this.arr = res.data;
      this.rolesAssignDialogVisible = true;
    },
    //确定添加
    async sureRolesAssign() {
      if (!this.seleteId) {
        return layer.msg("请选择新角色!", { time: 1000 });
      }
      const { data: res } = await this.axios.put(
        `users/${this.rolesAssignInfo.id}/role`,
        {
          rid: this.seleteId,
        }
      );
      if (res.meta.status !== 200) {
        return layer.msg(res.meta.msg, { time: 1000 });
      }
      layer.msg(res.meta.msg, { time: 1000 }, () => {
        this.getUserList();
        this.rolesAssignDialogVisible = false;
      });
    },
    closeRolesAssign() {
      this.seleteId = "";
      this.rolesAssignInfo = "";
    },
  },
};
</script>

<style scoped>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
p {
  line-height: 40px;
  font-size: 16px;
}
</style>



